<script lang="ts" setup>
import type { Recordable } from '@vben/types';

import type { VbenFormSchema } from '#/adapter/form';
import type { DictApi, DVMTAPI } from '#/api';

import { computed, reactive, ref } from 'vue';

import { useVbenDrawer } from '@vben/common-ui';
import { getPopupContainer } from '@vben/utils';

import { breakpointsTailwind, useBreakpoints } from '@vueuse/core';

import { useVbenForm } from '#/adapter/form';
import {
  DictResp,
  getMachineryTypeHandleList,
  updateMachineryTypeMenu,
} from '#/api';
// import {
//   createMenu,
//   getMenuList,
//   isMenuNameExists,
//   isMenuPathExists,
//   SystemMenuApi,
//   updateMenu,
// } from '#/api/system/menu';
import { $t } from '#/locales';
import { messageSuccess } from '#/utils';

const sys_yes_no = reactive<DictApi.SelectOption[]>([]);

DictResp(['sys_yes_no']).then((res) => {
  // 将两个数组合并
  if (res.sys_yes_no) {
    sys_yes_no.push(...res.sys_yes_no);
  }
});

const formData = ref<DVMTAPI.Datum>();
const titleSuffix = ref<string>();
const schema: VbenFormSchema[] = [
  {
    component: 'Input',
    fieldName: 'machineryTypeId',
    label: 'id',
    dependencies: {
      triggerFields: ['machineryTypeId'],
      show() {
        return false;
      },
    },
  },
  {
    component: 'ApiTreeSelect',
    componentProps: {
      api: getMachineryTypeHandleList,
      class: 'w-full',
      filterTreeNode(input: string, node: Recordable<any>) {
        if (!input || input.length === 0) {
          return true;
        }
        const title: string = node.machineryTypeName ?? '';
        if (!title) return false;
        return title.includes(input) || $t(title).includes(input);
      },
      getPopupContainer,
      labelField: 'machineryTypeName',
      showSearch: true,
      treeDefaultExpandAll: true,
      valueField: 'machineryTypeId',
      childrenField: 'children',
    },
    fieldName: 'parentTypeId',
    label: '父类型',
    formItemClass: 'col-span-2',
    dependencies: {
      triggerFields: ['machineryTypeId'],
      if(values) {
        return values.machineryTypeId !== 1;
      },
    },
  },
  {
    component: 'Input',
    fieldName: 'machineryTypeName',
    label: '设备类型名称',
    rules: 'required',
  },
  {
    component: 'RadioGroup',
    componentProps: {
      options: sys_yes_no,
    },
    rules: 'required',
    fieldName: 'enableFlag',
    label: '是否启用',
  },
  {
    component: 'Textarea',
    componentProps: {
      placeholder: '请输入备注信息',
      maxLength: 50,
      rows: 3,
      showCount: false,
    },
    fieldName: 'remark',
    label: '备注',
    emptyStateValue: null,
    formItemClass: 'col-span-2',
  },
];

const breakpoints = useBreakpoints(breakpointsTailwind);
const isHorizontal = computed(() => breakpoints.greaterOrEqual('md').value);

const [Form, formApi] = useVbenForm({
  commonConfig: {
    colon: true,
  },
  schema,
  showDefaultActions: false,
  wrapperClass: 'grid-cols-2 gap-x-4',
});

const [Drawer, drawerApi] = useVbenDrawer({
  onConfirm: onSubmit,
  onOpenChange(isOpen) {
    if (isOpen) {
      const data = drawerApi.getData<DVMTAPI.Datum>();
      if (data) {
        formData.value = data;
        formApi.setValues(formData.value);
        titleSuffix.value = formData.value.machineryTypeName
          ? $t(formData.value.machineryTypeName)
          : '';
      } else {
        formApi.resetForm();
        titleSuffix.value = '';
      }
    }
  },
});

async function onSubmit() {
  const { valid } = await formApi.validate();
  if (valid) {
    drawerApi.lock();
    let data;
    await formApi.getValues().then((res) => {
      data = res;
    });
    try {
      await (formData.value?.machineryTypeId
        ? updateMachineryTypeMenu(data!)
        : updateMachineryTypeMenu(data!));
      drawerApi.close();
      messageSuccess(`修改成功`);
    } finally {
      formApi.resetForm();
      drawerApi.unlock();
    }
  }
}
const getDrawerTitle = computed(() => {
  if (formData.value?.attr1 === '1')
    return `查看${formData.value?.machineryTypeName}`;
  return formData.value?.attr1 === '2'
    ? `编辑${formData.value?.machineryTypeName}`
    : `新增类型`;
});
</script>
<template>
  <Drawer class="w-full max-w-[800px]" :title="getDrawerTitle">
    <Form class="mx-4" :layout="isHorizontal ? 'horizontal' : 'vertical'" />
  </Drawer>
</template>
